<?php

namespace App\Api\Controllers;

use App\Models\User;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use EasyWeChat\Foundation\Application;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Facades\JWTAuth;

/**
 * Class WxLoginController
 * @package App\Api\Controllers
 * 微信登录
 * 整个应用中不需要使用session，均使用jwt的token作为用户凭证
 */
class WxLoginController extends Controller
{
    use AuthenticatesUsers;
    use Helpers;
    private $wechat;
    public function __construct(Application $wechat)
    {
        $this->wechat=$wechat;
    }

    /**
     * 名称：微信登录
     * 必要条件：code,放置在url中
     * 功能：需要返回token
     * 任务：
     * 1.通过code去获取用户openid和accesstoken
     * 2.查询users表若有此用户则返回认证token,
     * 3.若没有此用户则通过accesstoken去获取用户信息插入自己的数据库后返回token
     */
    public function wxLogin(Request $request)
    {
        if(strlen($request->code)<=7 && $request->state=='chenyu'){
            //模拟登录
            $user=User::find($request->code);
            goto down;
        }
        //通过，下面是真正的微信登录
        $authUser=$this->wechat->oauth->user();
        // 获取 OAuth 授权结果用户信息
        $originData = $authUser->getOriginal();//竟然返回的是array,握草
        if(!$originData){
            return $this->response()->array([
                'status_code' => 201,
                'message' => '1.认证失败'
            ]);
        }
        $user=User::where('openid',$originData['openid'])->first();
        if(!$user){
            $dataIn=[
                'nickname'=>deal_emoji($originData['nickname'],0),
                'phone_number'=>'',
                'password'=>'',
                'gender'=>$originData['sex'],
                'balance'=>0,
                'openid'=>$originData['openid'],
                'campus_id'=>0,
                'university_id'=>0,
                'address'=>'',
                'head_img'=>$originData['headimgurl'],
                'subscribe'=>0,
                'city'=>$originData['city'],
                'province'=>$originData['province'],
                'country'=>$originData['country'],
                'subscribe_time'=>time(),
                'remark'=>'',
                'manager'=>0,
                'share_code'=>uniqid(),
                'spread_uid'=>0,
                'spread_status'=>0,
                'spread_qrcode'=>''

            ];
            $user=User::create($dataIn);

        }
        down:
        if(!$user){
            return $this->response()->array([
                'status_code' => 201,
                'message' => '2.认证失败'
            ]);
        }else{
            $token = JWTAuth::fromUser($user);
            return $this->response()->array([
                'result' => ['token'=>$token],
                'status_code' => 200,
                'message' => '认证成功'
            ]);
        }
    }

    /**
     * 名称：微信认证需要跳转的链接
     * 必要条件：
     * 功能：返回认证用户的链接
     * 任务：
     */
    public function snsapiUserinfoUrl()
    {
        $host=request()->getSchemeAndHttpHost();
        //返回拼接好的链接给前端去跳转微信链接
        $response = $this->wechat->oauth->scopes(['snsapi_userinfo'])
            ->redirect($host.'/www/signin');
        return $this->response->array([
            'status_code'=>200,
            'message_code'=>'获取数据成功',
            'result'=>['url'=>$response->getTargetUrl()]
        ]);
    }

    /**
     * 名称：退出登录
     * 必要条件：
     * 功能：
     * 任务：
     */
    public function logout(){

        $this->guard()->logout();
    }




}